package com.example.dmservice.excelInput.service;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.example.dmcommom.SpringBeanHelper;
import com.example.dmdomain.ProvinceRepository;
import com.example.dmdomain.entity.ProvinceCity;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class CityListener implements ReadListener<ProvinceCity> {

	private static final int BATCH_COUNT = 100;

	private List<ProvinceCity> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

	@Override
	public void invoke(ProvinceCity data, AnalysisContext context) {

		if (data != null && data.getId() != null) {
			log.info("解析到一条数据:{}", JSON.toJSONString(data));
			cachedDataList.add(data);
		} else {
			return;
		}

		if (cachedDataList.size() >= BATCH_COUNT) {
			saveData();
			cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
		}
	}

	private void saveData() {
		ProvinceRepository repository = SpringBeanHelper.getBeanOrThrow(ProvinceRepository.class);
		repository.saveAll(cachedDataList);
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext context) {
		log.info("finished");
	}
}
